from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from datetime import datetime

from app.api import deps
from app.schemas import airticket_flight as schemas
from app.database.models.erp import AirticketOrder, AirticketOrderFlight
from app.database.models.base import User

router = APIRouter()

@router.get("/orders/{airticket_order_id}/flights", response_model=List[schemas.AirticketOrderFlight])
def list_airticket_flights(
    airticket_order_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取指定机票订单的所有航班信息"""
    try:
        # 检查机票订单是否存在并验证权限
        order = db.query(AirticketOrder).filter(AirticketOrder.ID == airticket_order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Airticket order not found")
        
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 获取航班列表
        flights = db.query(AirticketOrderFlight).filter(
            AirticketOrderFlight.airticket_order_id == airticket_order_id
        ).all()
        
        return flights
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Error fetching flights: {str(e)}"
        )

@router.post("/orders/{airticket_order_id}/flights", response_model=schemas.AirticketOrderFlight)
def create_airticket_flight(
    *,
    db: Session = Depends(deps.get_db),
    airticket_order_id: int,
    flight_in: schemas.AirticketOrderFlightCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """为机票订单添加航班信息"""
    try:
        # 检查机票订单是否存在并验证权限
        order = db.query(AirticketOrder).filter(AirticketOrder.ID == airticket_order_id).first()
        if not order:
            raise HTTPException(status_code=404, detail="Airticket order not found")
        
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 创建航班记录
        flight_data = flight_in.dict()
        flight_data["airticket_order_id"] = airticket_order_id
        
        flight = AirticketOrderFlight(**flight_data)
        db.add(flight)
        db.commit()
        db.refresh(flight)
        return flight
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/flights/{flight_id}", response_model=schemas.AirticketOrderFlight)
def update_airticket_flight(
    *,
    db: Session = Depends(deps.get_db),
    flight_id: int,
    flight_in: schemas.AirticketOrderFlightUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新航班信息"""
    try:
        # 获取航班记录
        flight = db.query(AirticketOrderFlight).filter(
            AirticketOrderFlight.ID == flight_id
        ).first()
        if not flight:
            raise HTTPException(status_code=404, detail="Flight not found")

        # 检查权限
        order = db.query(AirticketOrder).filter(
            AirticketOrder.ID == flight.airticket_order_id
        ).first()
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 更新航班信息
        update_data = flight_in.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(flight, field, value)

        db.add(flight)
        db.commit()
        db.refresh(flight)
        return flight
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/flights/{flight_id}")
def delete_airticket_flight(
    *,
    db: Session = Depends(deps.get_db),
    flight_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除航班信息"""
    try:
        # 获取航班记录
        flight = db.query(AirticketOrderFlight).filter(
            AirticketOrderFlight.ID == flight_id
        ).first()
        if not flight:
            raise HTTPException(status_code=404, detail="Flight not found")

        # 检查权限
        order = db.query(AirticketOrder).filter(
            AirticketOrder.ID == flight.airticket_order_id
        ).first()
        if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 删除航班记录
        db.delete(flight)
        db.commit()
        return {"ok": True}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e)) 